package com.music.note_android.data.model

import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
import java.util.UUID

/**
 * 文件夹数据模型
 * 对应MVP02_文件夹管理模块需求
 */
@Entity(tableName = "folders")
data class Folder(
    @PrimaryKey
    val id: String = UUID.randomUUID().toString(),
    
    @ColumnInfo(name = "name")
    val name: String,
    
    @ColumnInfo(name = "created_time")
    val createdTime: Long,
    
    @ColumnInfo(name = "is_system")
    val isSystem: Boolean = false,
    
    // 这个字段不存储在数据库中，用于显示笔记数量
    @androidx.room.Ignore
    val noteCount: Int = 0
) {
    // 辅助构造函数，用于Room查询时创建对象
    constructor(
        id: String,
        name: String,
        createdTime: Long,
        isSystem: Boolean
    ) : this(id, name, createdTime, isSystem, 0)
    
    /**
     * 获取格式化的创建时间
     */
    fun getFormattedCreatedTime(): String {
        return formatTime(createdTime)
    }
    
    /**
     * 时间格式化辅助方法
     */
    private fun formatTime(timestamp: Long): String {
        val now = System.currentTimeMillis()
        val diff = now - timestamp
        
        return when {
            diff < 60 * 1000 -> "刚刚"
            diff < 60 * 60 * 1000 -> "${diff / (60 * 1000)}分钟前"
            diff < 24 * 60 * 60 * 1000 -> "${diff / (60 * 60 * 1000)}小时前"
            diff < 7 * 24 * 60 * 60 * 1000 -> "${diff / (24 * 60 * 60 * 1000)}天前"
            else -> {
                val date = java.util.Date(timestamp)
                val format = java.text.SimpleDateFormat("yyyy-MM-dd", java.util.Locale.getDefault())
                format.format(date)
            }
        }
    }
    
    /**
     * 获取笔记数量的显示文本
     */
    fun getNoteCountText(): String {
        return when (noteCount) {
            0 -> "空文件夹"
            else -> "${noteCount}个笔记"
        }
    }
    
    /**
     * 是否可以删除
     * 系统文件夹和非空文件夹不能删除
     */
    fun canDelete(): Boolean {
        return !isSystem && noteCount == 0
    }
    
    /**
     * 是否可以重命名
     * 系统文件夹不能重命名
     */
    fun canRename(): Boolean {
        return !isSystem
    }
}

/**
 * 系统文件夹常量
 */
object SystemFolders {
    const val ALL_NOTES = "all_notes"
    const val UNCATEGORIZED = "uncategorized"
    
    val ALL_NOTES_FOLDER = Folder(
        id = ALL_NOTES,
        name = "所有笔记",
        createdTime = 0,
        isSystem = true
    )
    
    val UNCATEGORIZED_FOLDER = Folder(
        id = UNCATEGORIZED,
        name = "未分类",
        createdTime = 0,
        isSystem = true
    )
    
    /**
     * 获取所有系统文件夹
     */
    fun getSystemFolders(): List<Folder> {
        return listOf(ALL_NOTES_FOLDER, UNCATEGORIZED_FOLDER)
    }
    
    /**
     * 检查是否为系统文件夹ID
     */
    fun isSystemFolder(folderId: String): Boolean {
        return folderId == ALL_NOTES || folderId == UNCATEGORIZED
    }
}